#include <glut.h>

GLfloat eyex = 0;
GLfloat eyey = 0;
GLfloat eyez = 0.2;

unsigned char color = 1;
unsigned char counter = 0;

void renderScene()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();	

	gluLookAt(eyex, eyey, eyez, 0, 0, 0, 0, 1, 0);

	glTranslatef(-2.f, 1.5, -4.f);
	glBegin(GL_TRIANGLES);
		glColor3f(0, 1, 0);
		glVertex3f(0, 1, 0);
		glVertex3f(-1, -1, 0);
		glVertex3f(1, -1.f, 0.f);
	glEnd();

	glColor3f(1, 1, 1);
	glTranslatef(3.f, 0.f, 0.f);

	glBegin(GL_TRIANGLE_FAN);
		// 1
		glVertex3f(-1.f, 1.f, 0.f);
		glVertex3f(1.f, 1.f, 0.f);
		glVertex3f(1.f, -1.f, 0.f);
		// 2
		glVertex3f(-1.f, -1.f, 0.f);
	glEnd();

	glTranslatef(-3.f, -3.f, 0.f);

	glBegin(GL_TRIANGLE_FAN);
		// 1
		glColor3f(float(color & 1), float(color & 2), float(color & 4));
		glVertex3f(0, 1, -0);
		glVertex3f(1, 0.2, -0);
		glVertex3f(-1, 0.2, -0);
		// 2
		glVertex3f(-0.7, -1, -0);
		// 3
		glVertex3f(0.7, -1, -0);
		// 4
		glVertex3f(1, 0.2, -0);
	glEnd();

	glutSwapBuffers();
}

void changeColorTimer(int timerId)
{
	if(counter < 2)
	{
		color <<= 1;
		counter++;
	}
	else 
	{
		counter = 0;
		color = 1;
	}

	glutTimerFunc(1000, changeColorTimer, 0);
}

void processNormaKeys(unsigned char key, int x, int y)
{
	switch(key)
	{
	case 27:
		exit(0);
	}
}

void processSpecialKeys(int key, int x, int y)
{
	switch(key)
	{
	case GLUT_KEY_UP:
		eyey -= 0.1;
		break;
	case GLUT_KEY_DOWN:
		eyey += 0.1;
		break;
	case GLUT_KEY_LEFT:
		eyex -= 0.1;
		break;
	case GLUT_KEY_RIGHT:
		eyex += 0.1;
		break;
	case GLUT_KEY_HOME:
		eyez -= 0.1;
		break;
	case GLUT_KEY_END:
		eyez += 0.1;
		break;
	}
}

int main(int argc, char** argv)
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
	glutInitWindowSize(640, 640);
	glutCreateWindow("Ex3");
	glutDisplayFunc(renderScene);
	glutIdleFunc(renderScene);
	glutKeyboardFunc(processNormaKeys);
	glutSpecialFunc(processSpecialKeys);
	glutTimerFunc(1000, changeColorTimer, 0);

	glMatrixMode(GL_PROJECTION);
	gluPerspective(90, 1.0, 0, 400);

	glMatrixMode(GL_MODELVIEW);

	glutMainLoop();

	return 0;
}